package br.com.ac.fatureweb.utilitary.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.ac.fatureweb.utilitary.FacesUtils;

@FacesConverter("cpfCnpjConverter")
public class CpfCnpjConverter implements Converter
{

	/*
	 * (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(final FacesContext ctx, final UIComponent comp,
			final String value)
	{
		if ( value != null )
		{
			if ( value.length() == 18 )
			{
				return new String(value.replaceAll("\\.", "").replaceAll("/", "")
						.replaceAll("-", ""));
			}
			else if ( value.length() == 14 )
			{
				return new String(value.replaceAll("\\.", "").replaceAll("-", ""));
			}

			/*
			 * Caso o campo não obedeça a quantidade mínima de dígitos.
			 */
			if ( value.length() < 14 )
			{
				FacesUtils
						.addMessageError("O CPF deve estar no formato 000.000.000-00");
			}
			else
			{
				FacesUtils
						.addMessageError("O CNPJ deve estar no formato 00.000.000/0000-00");
			}
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(final FacesContext ctx, final UIComponent comp,
			final Object value)
	{
		if ( value != null )
		{
			if ( value.toString().length() == 14 )
			{
				return formatarCnpj(value.toString());
			}
			else if ( value.toString().length() == 11 )
			{
				return formatarCpf(value.toString());
			}
		}

		return "";
	}

	private String formatarCpf(final String value)
	{
		final StringBuilder sb = new StringBuilder();
		final String tmp = value.toString();

		sb.append(tmp.substring(0, 3));
		sb.append('.');
		sb.append(tmp.substring(3, 6));
		sb.append('.');
		sb.append(tmp.substring(6, 9));
		sb.append('-');
		sb.append(tmp.substring(9, 11));

		return sb.toString();
	}

	private String formatarCnpj(final String value)
	{
		final StringBuilder sb = new StringBuilder();
		final String tmp = value.toString();

		sb.append(tmp.substring(0, 2));
		sb.append('.');
		sb.append(tmp.substring(2, 5));
		sb.append('.');
		sb.append(tmp.substring(5, 8));
		sb.append("/");
		sb.append(tmp.substring(8, 12));
		sb.append('-');
		sb.append(tmp.substring(12, 14));

		return sb.toString();
	}
}
